<?php
namespace backend\controllers;

use Yii;
use common\helps\tools;
use yii\web\AdminController;
use backend\models\GoodsBrand;
use backend\models\UploadForm;
use backend\models\BannerConfig;
use backend\models\HotSaleConfig;
use common\helps\redisHelper;
use backend\models\BrandStreetCategory;

class BrandPictureController extends AdminController
{
    public $layout = false;
    //业务关键字
    public $service = 'BrandPicture';
    
    public $type = 9;
    
    public function actionIndex()
    {
        $model = new UploadForm();
		//add by lizenan 20180309 【后台需求】首页品牌街有点击更多的按钮（此按钮在设计中），点击更多，新增一页品牌街列表页。 533 start
        $brand = GoodsBrand::find()->select('id,brand_name')->where('use_flg=1')->orderBy(array('brand_name'=> 'asc'))->asArray()->all();
        $brand_category = BrandStreetCategory::find()->select('id,name')->where('use_flg='.BrandStreetCategory::STATUS_ENABLE)->asArray()->all();
        return $this->render('index',['brand'=>$brand,'model'=>$model,'brand_category'=>$brand_category]);
		//add by lizenan 20180309 【后台需求】首页品牌街有点击更多的按钮（此按钮在设计中），点击更多，新增一页品牌街列表页。 533 end
    }

    /**
     * 取得列表数据
     * @return string
     */
    public function actionGetBrandPicture(){
        $data = Yii::$app->request->post();
        $type = $this->type;
        $str_where = 'type='.$type;
        if($data['platform'] != ''){
            $str_where = $str_where . ' and platform = ' . $data['platform'];
        }
        $query = HotSaleConfig::find()->select('id,sort,brand_id,platform,use_flg')->where($str_where);
        $count = $query->count();
        $list = $query->offset($data['start'])->limit($data['length'])
                       ->orderBy(array('sort'=>$data['order'][0]['dir'] == 'asc' ? SORT_ASC : SORT_DESC))->asArray()->all();

        $result_val = [];
        if (count($list) > 0){
            $brand_id = array_column($list, 'brand_id');
            $brand = [];
            if (count($brand_id) > 0){
                $brand = GoodsBrand::find()->select('id,brand_name')->where(['in','id',$brand_id])->asArray()->all();
                $brand = array_combine(array_column($brand, 'id'), $brand);
            }
            $id = array_column($list, 'id');
            $banner_config = BannerConfig::find()->where(['in','group_id',$id])->asArray()->all();
            $banner_config_arr = [];
            if (is_array($banner_config) && count($banner_config) > 0)foreach ($banner_config as $banner){
                $banner_config_arr[$banner['group_id']][] = $banner;
            }
            foreach ($list as $val){
                $val['brand_name'] = tools::arrayHasValue($brand,$val['brand_id']) && tools::arrayHasValue($brand[$val['brand_id']],'brand_name') ? $brand[$val['brand_id']]['brand_name'] : '';
                $val['banner_config'] = $banner_config_arr[$val['id']];
                $result_val[] = $val;
            }
        }
        $result['draw'] = intval($data['draw']);
        $result['recordsTotal'] = intval($count);
        $result['recordsFiltered'] = intval($count);
        $result['data'] = $result_val;
        return \yii\helpers\Json::encode($result);
    }

    /**
     * 修改排序值
     * @throws \Exception
     */
    public function actionChangeBrandPictureSort(){
        $model = new HotSaleConfig();
        $data = Yii::$app->request->post();
        $id = $data['id'];
        $sort = $data['sort'];
        $data_new = [
            'sort'=>$sort,
            'editor'=>$model->getCreator(),
            'edit_time'=>date('Y-m-d H:i:s')
        ];
        $ret = $model::updateAll($data_new,['id'=>$id]);
        if(!$ret){
            throw new \Exception('操作失败');
        }
        $redis = new redisHelper();
        $redis->delFrontendNavMenu();
        $this->retJson('操作成功',200);
    }
    
    public function actionChangeBrandPictureStatus(){
        $model = new HotSaleConfig();
        $data = Yii::$app->request->post();
        $id = $data['id'];
        $use_flg = $data['use_flg'];
        $data_new = [
            'use_flg'=>$use_flg,
            'editor'=>$model->getCreator(),
            'edit_time'=>date('Y-m-d H:i:s')
        ];
        $ret = $model::updateAll($data_new,['id'=>$id]);
        if(!$ret){
            throw new \Exception('操作失败');
        }
        $redis = new redisHelper();
        $redis->delFrontendNavMenu();
        $this->retJson('操作成功',200);
    }
    
    public function actionBrandPictureDetail(){
        $data = Yii::$app->request->post();
        $id = $data['id'];
		//add by lizenan 20180309 【后台需求】首页品牌街有点击更多的按钮（此按钮在设计中），点击更多，新增一页品牌街列表页。 533 start
        $brandPicture = HotSaleConfig::find()->where('id=:id',[':id'=>$id])->asArray()->one();
        if (count($brandPicture) > 0){
            $banner_config = BannerConfig::find()->where('group_id='.$id)->orderBy('sort asc')->asArray()->all();
            $brandPicture['banner_config'] = $banner_config;
            $brandPicture['brand_street_category_id'] = array_filter(array_unique(array_column($banner_config, 'brand_street_category_id')));
        }
        $this->retJson($brandPicture,200);
    }
    
    public function actionChangeBrandPicture(){
        $model = new HotSaleConfig();
        $data = Yii::$app->request->post();
        $transaction = Yii::$app->db->beginTransaction();
        try {
            $oper = $model->getCreator();
            $oper_time = date('Y-m-d H:i:s');
            $brand_id = $data['brand_id'];
            $platform = $data['platform'];
            $hot_sale_id = $data['hot_sale_id'];
            $use_flg = $data['use_flg'];
            $picture_name = $data['picture_name'];
            $sort = $data['sort'];
            $picture_url = $data['picture_url'];
//             $picture_alt = $data['picture_alt'];
            $product_url = $data['product_url'];
            $type = $this->type;
            $brand_list_picture_url = tools::arrayHasValue($data,'brand_list_picture_url') ? $data['brand_list_picture_url'] : '';
            $brand_interactive_picture_url = tools::arrayHasValue($data,'brand_interactive_picture_url') ? $data['brand_interactive_picture_url'] : '';
            $brand_category = tools::arrayHasValue($data,'brand_category') ? array_filter($data['brand_category']) : '';
            $is_show = tools::arrayHasValue($data,'is_show') ? $data['is_show'] : '';
            if (!$brand_id){
                throw new \Exception('请选择品牌');
            }
            if (!$picture_name){
                throw new \Exception('请填写活动图片名称');
            }
            if (!$sort){
                throw new \Exception('请填写活动排序编号');
            }
            if (!$picture_url){
                throw new \Exception('请上传一张商品图片');
            }
            //del by allen.qiang 20171205 不需要必填 start
            //if (!$product_url){
            //    throw new \Exception('请填写商品链接');
            //}
            //del by allen.qiang 20171205 不需要必填 end
            if ($hot_sale_id){
                $model = HotSaleConfig::findOne($hot_sale_id);
                $model->editor = $oper;
                $model->edit_time = $oper_time;
                $where_banner['group_id'] = $hot_sale_id;
                BannerConfig::deleteAll('group_id='.$hot_sale_id);
            }else{
                $model->category_id = 0;
                $model->creator = $oper;
                $model->create_time = $oper_time;
                $model->type = $type;
            }
            $model->is_show = $is_show;
            $model->platform = $platform;
            $model->brand_id = $brand_id;
            $model->sort = $sort;
            $model->use_flg = $use_flg;
            $model->save();
            $hot_sale_id = $model->attributes['id'];
            if (!$hot_sale_id){
                throw new \Exception('活动维护失败');
            }
            $values = [];
            $fields = [
                'group_id',
                'picture_name',
                'picture_url',
                'brand_list_picture_url',
                'brand_interactive_picture_url',
                'brand_street_category_id',
                'product_url',
                'sort',
                'creator',
                'create_time',
                'editor',
                'edit_time'
            ];
            if (count($brand_category) > 0)foreach ($brand_category as $key=>$brand_street_category_id){
                $values[] = [
                    $hot_sale_id,
                    $picture_name,
                    $picture_url,
                    $brand_list_picture_url,
                    $brand_interactive_picture_url,
                    $brand_street_category_id,
                    $product_url,
                    $key+1,
                    $oper,
                    $oper_time,
                    $oper,
                    $oper_time
                ];
            }else{
                $values[] = [
                    $hot_sale_id,
                    $picture_name,
                    $picture_url,
                    $brand_list_picture_url,
                    $brand_interactive_picture_url,
                    '',
                    $product_url,
                    1,
                    $oper,
                    $oper_time,
                    $oper,
                    $oper_time
                ];
            }
            $banner_config = Yii::$app->db->createCommand()->batchInsert('j_banner_config', $fields, $values)->execute();
            if(!$banner_config){
                throw new \Exception('操作失败');
            }
			//add by lizenan 20180309 【后台需求】首页品牌街有点击更多的按钮（此按钮在设计中），点击更多，新增一页品牌街列表页。 533 end
            $redis = new redisHelper();
            $redis->delFrontendNavMenu();
            $transaction->commit();
            $this->retJson('编辑成功',200);
        } catch (\Exception $e) {
            $transaction->rollBack();
            //add by allen.qiang 20180112 异常处理，日志优化 start
            error_log('error->' . __METHOD__ . ' error:' . $e->getMessage());
            //add by allen.qiang 20180112 异常处理，日志优化 end
            $this->retJson($e->getMessage(),500);
        }
    }
}